const axios = require('axios');
const { promisify } = require('util');
const inquirer = require('inquirer');
const ora = require('ora');
let downloadFn = require('download-git-repo');

downloadFn = promisify(downloadFn); // 让 downloadFn 支持async + await   



// 工具方法：添加耗时等待
const addLoading = function (fn) {

    return async function (...args) {
        const spinner = ora('拉取开始....');
        spinner.start();
        try {
            let ret = await fn(...args);
            spinner.succeed('拉取成功')
            return ret;
        } catch (error) {
            console.log(error)
            spinner.fail('拉取失败');
        }
    }

}
// 工具方法：获取仓库列表
const fetchRepoList = async function () {
    const { data } = await axios.get('https://api.github.com/users/zcegg/repos')
    const repos = data.map(item => item.name)
    return repos;
}

// 工具方法：获取 tags 列表
const fetchTagList = async function (tmpname) {
    const { data } = await axios.get(`https://api.github.com/repos/zcegg/${tmpname}/tags`)
    const repos = data.map(item => item.name)
    return repos;
}

// 工具方法：自定义函数完成 git 仓库下载操作
const downloadRepo = function (repo, tag) {
    // download-git-repo + 缓存
    //1 定义缓存目录
    let cacheDir = `${process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME']}/.tmp`

    // 2 处理download-git-repo 函数的调用规则 downloadFn(zcegg/create-nm#tagv)
    let api = `zecgg/${repo}`
    if (tag) {
        api += `#${tag}`
    }

    console.log(cacheDir);
    console.log(api);
}


module.exports = async (pramas) => {

    //1 获取模板列表
    const repos = await addLoading(fetchRepoList)();

    //2 交互问题
    let { tmpname } = await inquirer.prompt({
        type: 'list',
        name: 'tmpname',
        message: '请选择目标仓库模板',
        choices: repos,
    })
    console.log(tmpname);

    //3 拉取 tags ， tags可能为有值数组或空数组
    const tags = await addLoading(fetchTagList)(tmpname);

    console.log(tags);


    // tags分支处理 [v1,v2,v3.....]  []
    if (tags.length) {
        // 仓库存在多个tag
        let { tagv } = await inquirer.prompt({
            type: 'list',
            name: 'tagv',
            message: '请选择目标版本',
            choices: tags,
        })
        console.log(tagv);
        downloadRepo(tmpname, tagv)
    } else {
        //  仓库不存在多个 tags 版本
        let { isDownload } = await inquirer.prompt({
            type: 'confirm',
            name: 'isDownload',
            message: '当前不存在多个tag是否直接下载',
        })

        if (isDownload) {
            console.log('选择yes直接执行下载操作');
            downloadRepo(tmpname, '');
        } else {
            return;
        }
    }


}


